<template>
    <div>
        <div class="top-img"><img src="../../assets/imgs/logo.png" alt=""></div>
        <el-menu class="menu" ref="menu" :style="level>1?{paddingTop: '50px'}:{}" :default-openeds="openMenu"
                 unique-opened :background-color="containerbgColor">
            <el-submenu v-if="menu.children" :index="menu.name" v-for="(menu,index) in menus" :key="menu.text">
                <template slot="title">
                    <i :class="menu.icon"></i>
                    {{menu.text}}
                </template>
                <el-menu-item-group v-if="menu.name==='pageSetting'">
                    <el-menu-item class="pageMenu" v-for="(m,i) in pageMenu" :key="pageMenu.path"
                                  @click="menuClick(m.path)"
                                  :class="active===m.path?'active':''">
                        <div style="color: #ffffff">{{i+1+'. ' }}{{m.text}}</div>
                        <span class="box">
                            <i class="el-icon-paperclip tip"></i>
                            <span class="p-btn">
                                <el-button style="margin-left: 20px" type="text" size="mini"
                                           :disiabled="i>=pageMenu.length-1"
                                           @click.prevent.stop="pBtnClick('up',i)" icon="el-icon-top"></el-button>
                                <el-button type="text" size="mini" @click.prevent.stop="pBtnClick('down',i)"
                                           icon="el-icon-bottom"></el-button>
                                <el-button type="text" size="mini" :disiabled="i<=0"
                                           @click.prevent.stop="pBtnClick('del',i)" icon="el-icon-delete"></el-button>
                             </span>
                        </span>
                    </el-menu-item>
                    <el-menu-item>
                        <el-button type="warning" size="mini" icon="el-icon-plus" @click="showModal">添加页
                        </el-button>
                    </el-menu-item>
                </el-menu-item-group>
                <el-menu-item-group v-else>
                    <el-menu-item v-if="m.name==='barrage'?isBarragePaid:true" v-for="m in menu.children"
                                  :key="m.text+m.name" @click="menuClick(m.path)" :class="active===m.path?'active':''">
                        <div style="color: #ffffff">{{m.text}}</div>
                    </el-menu-item>
                </el-menu-item-group>
            </el-submenu>
            <el-menu-item v-else @click="menuClick(menu.path)" :class="active===menu.path?'active':'back'+menu.icon">
                <router-link class="link-a" :to="menu.path"><i v-if="menu.icon" :class="menu.icon"></i>{{menu.text}}
                </router-link>
            </el-menu-item>
        </el-menu>
        <modal :width="800" :visible="modalVisible" @close="modalVisible=false" :top="50">
            <el-form :rules="rules" :model="addMenu" ref="addForm" label-position="top" class="pageTypeList">
                <el-form-item label="场景页类型：" label-width="100px" prop="type">
                    <div class="page_block" v-for="type in menuType" :key="type.type" v-if="type.name!=='弹幕'">
                        <el-image
                                style="width:85%"
                                :src="type.imgs"
                                fit="fill" @click="setPageType(type)" lazy></el-image>
                        <span class="pageListName">{{ type.name }}</span>
                        <img :src="selectIcon" class="selectIcon" @click="setPageType(type)"
                             :class="{'selectActive':type.active}" alt/>
                    </div>
                    <el-divider></el-divider>
                </el-form-item>
                <el-form-item label="场景页类型：" v-if="addMenu.type == 'func_userDefined'">
                    <el-radio-group v-model="addMenu.userType" size="small">
                        <el-radio-button label="blankPage">添加空白页面</el-radio-button>
                        <el-radio-button label="func_userDefined">上传PPT</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="场景页名称：" label-width="100px" prop="name"
                              v-if="addMenu.userType !== 'func_userDefined'|| addMenu.type === 'func_scrollScreen'|| addMenu.type ==='func_signIn'||addMenu.type ==='func_prizeDraw'||addMenu.type ==='func_loopPlay'">
                    <el-input placeholder="请输入场景页名称" maxlength="24" show-word-limit
                              v-model.trim="addMenu.name" v-if="addMenu.userType !== 'func_userDefined'|| addMenu.type === 'func_scrollScreen'|| addMenu.type ==='func_signIn'||addMenu.type ==='func_prizeDraw'||addMenu.type ==='func_loopPlay'" style="width: 50%;"></el-input>
                </el-form-item>
                <el-form-item label="场景页元素展示类型："
                              v-if="addMenu.userType === 'func_userDefined'&&addMenu.type==='func_userDefined'">
                    <el-radio-group v-model="elemShowType" size="small">
                        <el-radio-button label="slide">图片模式</el-radio-button>
                        <el-radio-button label="shape">组件模式</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <uploadingPage v-if="addMenu.userType === 'func_userDefined' && addMenu.type==='func_userDefined'"
                               @getUploadingData="getUploadingData" ref="uploading"
                               :elemShowType="elemShowType"></uploadingPage>
            </el-form>
            <div class="button" style="width:100%;display:inline-block">
                <el-button class="createPage" @click="modalVisible=false">取消</el-button>
                <el-button class="createPage" @click="addPage" type="primary" v-if="addMenu.userType !== 'func_userDefined'">确定</el-button>
            </div>
        </modal>
    </div>
</template>

<script>
    import { routerConfig } from '../../router/routerConfig';
    import { getRouterInfoByType, dirList } from '../../router/routerInfo';
    import loadComponent from '../../router/lazyLoad';
    import uploadingPage from '../components/views/pageSetting/uploadingPage';
    import loopPlayImg from '../../assets/imgs/pageList/loopPlay.png';
    import prizeImg from '../../assets/imgs/pageList/prize.png';
    import scrollImg from '../../assets/imgs/pageList/scrollScreen1.png';
    import signInImg from '../../assets/imgs/pageList/signIn1.png';
    import userDefinedImg from '../../assets/imgs/pageList/userDefined1.png';
    import selectIcon from '../../assets/imgs/pageList/select.png';

    export default {
        components: {
            uploadingPage,
        },
        name: 'leftMenu',
        data() {
            return {
                menus: [],
                active: '',
                containerbgColor: this.$styleVariables.menuBgColor,
                level: 0,
                query: '',
                openMenu: [],
                pageMenu: [],
                selectIcon: selectIcon,
                elemShowType: 'slide',
                addMenu: {
                    name: '',
                    type: '',
                    userType: 'blankPage',
                },
                modalVisible: false,
                uploadModal: false,
                menuType: [],
                rules: {
                    name: [
                        { required: true, message: '请输入场景页名称', trigger: 'blur' },
                    ],
                    type: [
                        { required: true, message: '请选择场景页类型', trigger: 'change' },
                    ],
                },
                isBarragePaid: false,
                upConfig: {},
            };
        },
        created() {
        },
        watch: {
            level(newV, oldV) {
                // console.log('levelChange', oldV, newV);
                newV <= 1 ? sessionStorage.setItem('pageMenu', '') : null;

                // 设置左侧菜单
                this.initMenu();
                // 设置展开菜单
                // this.setOpenMenu();
            },
        },
        mounted() {
            // console.log('query', this.$route.query);
            this.query = this.$route.query;
            console.info(this.$route);
            //确定当前路由层级
            let info = getRouterInfoByType({ path: this.$route.path });
            if (info) {
                this.level = info.level > 1 ? 2 : 1;
            } else {
                this.level = 2;
            }
            //监听菜单变化，修改菜单显示
            this.$bus.$on('menuChange', (toInfo, query) => {
                query ? this.query = query : null;
                if (toInfo) {
                    this.level = toInfo.level > 1 ? 2 : 1;
                    if (toInfo.level === this.level && toInfo.level === 1) {
                        this.active = toInfo.path;
                    }
                }
            });
            //监听菜单变化，修改菜单显示
            this.$bus.$on('menuChange', (toInfo, query) => {
                query ? this.query = query : null;
                if (toInfo) {
                    this.level = toInfo.level > 1 ? 2 : 1;
                }
            });
            //监听刷新场景页菜单
            this.$bus.$on('menuRefresh', (path, pageId) => {
                console.log('menuRefresh', path, pageId);
                let pageMenu = JSON.parse(sessionStorage.getItem('pageMenu'));
                pageMenu.forEach(item => {
                    if (item.path === path) {
                        this.active = '/pageSetting/' + pageId + '_' + item.type;
                    }
                });
                this.setPageMenu(this.active);
            });
        },
        methods: {
            setPageType(item) {
                this.menuType.forEach((page, i) => {
                    if (page.id == item.id) {
                        item.active = true;
                        this.addMenu.type = item.type;
                    } else {
                        page.active = false;
                    }
                });
                console.info(this.addMenu.type);
            },
            menuClick(text) {
                this.active = text;
                this.$router.push({ path: text, query: this.$route.query });
            },
            setPageMenu(refresh, userDefault) {
                let pageMenu = null;
                if (!userDefault) {
                    pageMenu = sessionStorage.getItem('pageMenu');
                }
                if (!pageMenu || refresh) {
                    this.$api.get('/st_scene/pages', { sceneId: this.query.sceneId }, success => {
                        // console.log('res', success);
                        let arr = [];
                        success.forEach((item, i) => {
                            if (item.pageType === 6) {
                                item.name ? item.name : item.name = 'PPT幻灯片' + i;
                            }
                            dirList[item.type] ? arr.push({
                                path: '/pageSetting/' + item.pageId + '_' + item.type,
                                name: item.pageId,
                                dir: dirList[item.type],
                                text: item.name,
                                level: 3,
                                type: item.type,
                                parent: 'pageSetting',
                                pageType: item.pageType,
                            }) : null;
                        });
                        this.pageMenu = arr;
                        // arr.push({
                        //     'dir': 'components/views/pageSetting/loopPlay',
                        //     'level': 3,
                        //     'name': 'add6911',
                        //     'type': 'func_loopPlay',
                        //     'parent': 'pageSetting',
                        //     'path': '/pageSetting/add7397_func_loopPlay',
                        //     'text': 'qqqq',
                        // });
                        sessionStorage.setItem('pageMenu', JSON.stringify(arr));
                        this.addRouterInfo('pageSetting', arr, routerConfig);
                        sessionStorage.setItem('allRouter', JSON.stringify(routerConfig));
                        let allRouters = loadComponent(routerConfig);
                        this.$router.addRoutes(allRouters);
                        if (refresh) {
                            this.$router.push({ path: refresh, query: this.query });
                        } else {
                            this.setOpenMenu();
                            this.setMenuType();
                        }
                        // console.log('finaly', this.$router);
                    }, fal => {
                        this.$message.error(fal);
                        this.setOpenMenu();
                        this.setMenuType();
                    });

                } else {
                    this.pageMenu = pageMenu = JSON.parse(pageMenu);
                    this.addRouterInfo('pageSetting', pageMenu, routerConfig);
                    let allRouters = loadComponent(routerConfig);
                    this.$router.addRoutes(allRouters);
                    this.setOpenMenu();
                    this.setMenuType();
                }
            },
            initMenu(toInfo) {
                let info = toInfo ? toInfo : getRouterInfoByType({ path: this.$route.path });
                if ((toInfo && toInfo.path.indexOf('pageSetting') > -1) || this.$route.path.indexOf('pageSetting') > -1) {
                    info = { parent: 'pageSetting' };
                }
                this.menus = routerConfig[0].children.filter((item) => {
                    return item.level === this.level;
                });
                this.active = this.$route.path;
                this.level > 1 ? this.setPageMenu() : null;
                this.setOpenMenu();
            },
            setOpenMenu() {
                let info = getRouterInfoByType({ path: this.$route.path });
                if (this.$route.path.indexOf('pageSetting') > -1) {
                    info = { parent: 'pageSetting' };
                }
                this.active = this.$route.path;
                this.openMenu = [info.parent];
            },
            setMenuType() {
                if (this.$route.query.sceneId) {
                    let sceneList = JSON.parse(sessionStorage.getItem('sceneList'));
                    // console.log('list', sceneList);
                    let sceneInfo;
                    sceneList.forEach(scene => {
                        let sceneId = this.$route.query.sceneId;
                        // console.log('sceneId===scene.sceneId', sceneId, scene.sceneId);
                        if (parseInt(sceneId) === parseInt(scene.sceneId)) {
                            sceneInfo = scene;
                        }
                    });
                    let modules = sceneInfo ? JSON.parse(sceneInfo.moduleJson) : [];
                    // console.log('modules', modules);
                    let menuType = [];
                    modules.forEach((item, i) => {
                        console.info(item);
                        // 将弹幕从类型中排除
                        // console.log(item.type, item.type.indexOf('barrage'));
                        if (item.type.indexOf('barrage') < 0) {
                            let m = {
                                type: item.type,
                                name: item.name,
                                id: i,
                                active: false,
                            };
                            switch (item.type) {
                                case 'func_scrollScreen':
                                    //滚屏 
                                    m.imgs = scrollImg;
                                    break;
                                case 'func_signIn':
                                    //签到
                                    m.imgs = signInImg;
                                    break;
                                case 'func_prizeDraw':
                                    //抽奖
                                    m.imgs = prizeImg;
                                    break;
                                case 'func_userDefined':
                                    //自定义
                                    m.imgs = userDefinedImg;
                                    break;
                                case 'func_loopPlay':
                                    //轮播
                                    m.imgs = loopPlayImg;
                                    break;
                            }
                            menuType.push(m);
                        } else {
                            this.isBarragePaid = true;
                        }
                    });
                    this.menuType = menuType;
                }
            },
            showModal() {
                console.log(this.$router);
                let hasAdd = false;
                this.pageMenu.forEach(item => {
                    if (item.path.toString().indexOf('add') > -1) {
                        hasAdd = true;
                    }
                });
                if (hasAdd) {
                    this.$message.info('请先保存当前新增的场景页');
                } else {
                    this.modalVisible = true;
                }
            },
            addPage() {
                this.$refs.addForm.validate((res) => {
                    if (res) {
                        if (this.addMenu.userType != 'func_userDefined') {
                            let nameFlag = false;
                            this.pageMenu.forEach(item => {
                                if (item.text === this.addMenu.name) {
                                    nameFlag = true;
                                }
                            });
                            if (nameFlag) {
                                this.$message.info('场景页名称不能重复');
                                return false;
                            }
                            let m = {
                                dir: dirList[this.addMenu.type],
                                level: 3,
                                name: this.addMenu.name,
                                type: this.addMenu.type,
                                parent: 'pageSetting',
                                path: '/pageSetting/' + 'add' + parseInt(Math.random() * 10000) + '_' + this.addMenu.type,
                                text: this.addMenu.name,
                            };
                            this.pageMenu.push(m);
                            sessionStorage.setItem('pageMenu', JSON.stringify(this.pageMenu));
                            this.modalVisible = false;
                            this.addMenu = {
                                name: '',
                                type: '',
                            };
                            this.addRouterInfo('pageSetting', this.pageMenu, routerConfig);
                            let allRouters = loadComponent(routerConfig);
                            this.$router.addRoutes(allRouters);
                            this.$router.push({ path: m.path, query: this.$route.query });
                            this.active = m.path;
                        } else { //自定义页面
                            this.uploadModal = true;
                            this.modalVisible = false;
                        }
                    } else {
                        this.$message.info('请完善场景页信息');
                        return false;
                    }
                });
            },
            addRouterInfo(parentName, info, routerArr) {
                routerArr.forEach(item => {
                    if (item.name === parentName) {
                        item.children = item.children.concat(info);
                    } else {
                        if (item.children) {
                            this.addRouterInfo(parentName, info, item.children);
                        }
                    }
                });
            },
            pBtnClick(type, index) {
                let hasAdd = false;
                this.pageMenu.forEach(item => {
                    if (item.path.toString().indexOf('add') > -1) {
                        hasAdd = true;
                    }
                });

                switch (type) {
                    case 'up':
                        if (hasAdd) {
                            this.$message.info('请先保存新增的场景页');
                        } else {
                            if (index > 0) {
                                let c = Object.assign({}, this.pageMenu[index - 1]);
                                this.pageMenu[index - 1] = this.pageMenu[index];
                                this.pageMenu[index] = c;
                                this.savePageOrder();
                            }
                        }
                        break;
                    case 'down':
                        if (hasAdd) {
                            this.$message.info('请先保存新增的场景页');
                        } else {
                            if (index < this.pageMenu.length - 1) {
                                let c = Object.assign({}, this.pageMenu[index + 1]);
                                this.pageMenu[index + 1] = this.pageMenu[index];
                                this.pageMenu[index] = c;
                                this.savePageOrder();
                            }
                        }
                        break;
                    case 'del':
                        let roIn = this.pageMenu[index];
                        this.$confirm('确定删除场景页：' + roIn.text + '?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }).then(() => {
                            if (roIn.path.toString().indexOf('add') > -1) {
                                this.pageMenu.splice(index, 1);
                                this.pageMenu = this.pageMenu.slice();
                                console.log('aaaaaaaa', this.pageMenu);
                                if (this.pageMenu.length > 0) {
                                    this.$router.push({ path: this.pageMenu[0].path, query: this.$route.query });
                                } else {
                                    this.$router.push({ path: '/baseSetting/baseSettings', query: this.$route.query });
                                    this.openMenu = ['baseSetting'];
                                }
                                sessionStorage.setItem('pageMenu', JSON.stringify(this.pageMenu));
                            } else {
                                let param = {
                                    sceneId: this.$route.query.sceneId,
                                    pageidBigint: roIn.name,
                                    pageType: roIn.pageType,
                                };
                                this.$api.post('/stScenepage/delScenePage', param, success => {
                                    this.$message.success('删除成功');
                                    this.pageMenu.splice(index, 1);
                                    this.pageMenu = this.pageMenu.slice();
                                    if (this.pageMenu.length > 0) {
                                        this.$router.push({ path: this.pageMenu[0].path, query: this.$route.query });
                                    } else {
                                        this.$router.push({
                                            path: '/baseSetting/baseSettings',
                                            query: this.$route.query,
                                        });
                                        this.openMenu = ['baseSetting'];
                                    }
                                    sessionStorage.setItem('pageMenu', JSON.stringify(this.pageMenu));
                                }, fal => {
                                    this.$message.error(fal);
                                });
                            }
                        }).catch(() => {

                        });

                        break;
                }
                this.pageMenu = this.pageMenu.slice();
                sessionStorage.setItem('pageMenu', JSON.stringify(this.pageMenu));
            },
            savePageOrder() {
                let arr = [];
                this.pageMenu.forEach(item => {
                    arr.push({
                        pageId: item.name,
                    });
                });
                this.$api.post('/st_scene/page/sort', arr, success => {
                    this.$message.success('更新成功');
                }, fal => {

                });
            },
            getUploadingData() { //创建自定义页面
                console.info("新建页面");
                this.modalVisible = false;
                this.uploadModal = false;
                this.setPageMenu(null, true);
            },
        },
    };
</script>

<style lang="scss">
    .top-img {
        margin: 30px 10px;
        height: 110px;
        text-align: center;
        img {
            height: 100%;
            display: inline-block;
        }
    }

    .pageTypeList {
        margin-top: 10px;
        padding: 0px 10px;
        .page_block {
            display: inline-block;
            width: 25%;
            // margin-bottom: 2px;
            height: 145px;
            text-align: center;
            .pageListName {
                color: #333;
                // right: -18px;
                position: relative;
                top: -5px;
            }
        }
        .el-divider--horizontal {
            margin: 0px;
        }
        .selectIcon {
            display: none;
            position: relative;
            width: 32px;
            height: 32px;
            top: -43px;
            left: 47px;
        }
        .selectActive {
            display: block;
            position: relative;
            width: 32px;
            height: 32px;
            top: -75px;
            left: 137px;
        }
    }
    .createPage{
        border-radius: 15px;
    }
    .menu {
        @include container-bg;
        border-right: none;
        padding-left: 20px;
        position: relative;
        div.el-submenu__title {
            color: #FFFFFF;
            border-bottom-left-radius: 15px;
            border-top-left-radius: 15px;
            min-width: unset;
            height: 40px;
            line-height: 40px;
            margin: 10px 0;
            @include flex;
        }
        li.el-menu-item {
            /*color: #FFFFFF !important;*/
            border-bottom-left-radius: 15px;
            border-top-left-radius: 15px;
            min-width: unset;
            height: 40px;
            line-height: 40px;
            margin: 10px 0;
            @include flex;
        }
        li.el-menu-item:hover {
            color: $color-blue;
        }
        li.backiconfont.ss-backward {
            position: absolute;
            left: -10px;
            top: 0;
            width: 90%;
            font-size: 14px;
            padding-left: 30px !important;
            background: #D9A96A !important;
            @include right-radius(20px);
            & > a:hover {
                color: #efefef !important;
            }
        }
        .active {
            background: #303030 !important;
        }
        li.el-menu-item:before {
            content: ' ';
            display: block;
            position: absolute;
            height: 100%;
            left: -35px;
            top: 0;
            width: 10px;
            @include right-radius(20px);
            background: #D9A96A;
            transition: all .3s;
        }
        li.el-menu-item.active:before {
            left: -20px;
        }
        a {
            color: #FFFFFF;
        }
        .iconfont {
            color: #eeeeee;
            margin-right: 5px;
            vertical-align: bottom;
        }
        .ss-backward {
            position: relative;
            left: -3px;
            top: -2px;
        }
    }

    .button {
        text-align: center;
        margin: 22px;
        button {
            width: 100px;
            margin: 0 20px;
        }
    }

    .pageMenu {
        .box {
            height: 100%;
            width: 0;
            right: 0;
            top: 0;
            position: absolute;
            .tip {
                margin: auto 0 auto -30px;
                color: #1989FA;
            }
            .p-btn {
                @include left-radius(40px);
                transition: all 0.3s 0.5s;
                overflow: hidden;
                position: absolute;
                z-index: 9;
                top: 0;
                right: 0;
                width: 0;
                background: #1989FA;
                transform: translateX(140px);
                button {
                    margin: 0;
                    box-sizing: border-box;
                    overflow: hidden;
                }
                i {
                    padding: 5px 2px;
                    text-align: center;
                    transition: all 0.3s;
                    color: #FFFFFF;
                    border-radius: 5px;
                }
                i:hover {
                    /*transform: scale(1.2);*/
                    color: #FFFFFF;
                    background: $color-black-20;
                }
            }
        }
    }

    .pageMenu {
        .box:hover {
            width: auto;
            .tip {
                z-index: -1;
            }
            .p-btn {
                transform: translateX(0);
                width: auto;
            }
        }
    }

    .link-a:hover {
        color: #fefefe;
    }
</style>